package com.bms.admin.base.menu.web;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.bms.admin.base.index.model.NowUser;
import com.bms.admin.base.menu.entity.Menu;
import com.bms.admin.base.menu.service.IMenuService;
import com.bms.admin.base.role.entity.RoleMenu;
import com.bms.admin.base.role.service.IRoleMenuService;
import com.bms.admin.config.annotation.LoginUser;
import com.bms.admin.util.AnnoManageUtil;
import com.bms.auth.annotation.RequiresPermissions;
import com.bms.common.base.common.bean.Result;
import com.bms.common.base.common.exception.EnumSvrResult;
import com.bms.common.base.web.BaseController;
import com.feilong.core.Validator;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * <p>
 * 菜单管理  前端控制器
 * </p>
 *
 * @author xj
 * @since 2018-08-09
 */
@RestController
@RequestMapping("menu")
@Api(value="Menu-Api",tags="菜单管理")
public class MenuController extends BaseController {

	@Autowired
	private IMenuService menuService;

	@Autowired
	private IRoleMenuService roleMenuService;

	@ApiOperation("获取菜单列表")
	@GetMapping("list")
	@RequiresPermissions("menu:list")
    public Result list(@RequestParam(defaultValue = "1",required=false)Integer pageNum, @RequestParam(defaultValue = "20",required=false)Integer pageSize) {

	    Wrapper<Menu> menuWrapper = new EntityWrapper<Menu>()
				.orderBy("sorts", true);

	    List<Menu> menus = menuService.selectList(menuWrapper);

	    menus.forEach(item -> {
	        if (item.getParentId() != 0) {
	            item.setParentName(menuService.selectById(item.getParentId()).getTitle());
            } else {
	            item.setParentName("一级菜单");
            }
        });

		return json(menus);
    }

	@ApiOperation("获取菜单信息")
	@GetMapping("info/{menuId}")
	@RequiresPermissions("menu:info")
    public Result info(@PathVariable Long menuId){
		return json(menuService.selectById(menuId));
    }

    /**
     * 获取下拉菜单即非按钮菜单
     * @return
     */
    @ApiOperation("获取非btn菜单")
    @GetMapping("/select")
    @RequiresPermissions("menu:info")
    public Result select () {

        Wrapper<Menu> menuWrapper = new EntityWrapper<Menu>()
                .ne("type", 3);

        List<Menu> menus = menuService.selectList(menuWrapper);

        Menu root = new Menu() ;
        root.setId(0L);
        root.setTitle("一级菜单");
        root.setParentId(-1L);
        menus.add(0, root);

        return json(menus);
    }

	@Validated
	@ApiOperation("新增菜单")
	@PostMapping("save")
	@RequiresPermissions("menu:save")
	public Result save(@ApiIgnore @LoginUser NowUser nowUser, @RequestBody Menu menu){
		Date now = new Date();
		menu.setCreateTime(now);
		menu.setCreateUser(nowUser.getUsername());
		menu.setUpdateTime(now);
		menuService.insert(menu);
		return success();
	}

	@Validated
	@ApiOperation("修改菜单信息")
	@PostMapping("update")
	@RequiresPermissions("menu:update")
	public Result update(@ApiIgnore @LoginUser NowUser nowUser,@RequestBody Menu menu){
		menu.setUpdateTime(new Date());
		menu.setUpdateUser(nowUser.getUsername());
		menuService.updateById(menu);
		return success();
	}

	@ApiOperation("删除菜单")
	@DeleteMapping("/delete")
	@RequiresPermissions("menu:delete")
    public Result delete(@RequestBody List<Long> menuIds) {
		List<RoleMenu> roleMenus = roleMenuService.queryRoleMenuByMenuIds(menuIds);
		if(Validator.isNotNullOrEmpty(roleMenus)){
			return fail(EnumSvrResult.ERROR_DEL_MENU);
		}
		List<Menu> parentIds = menuService.queryListParentIds(menuIds);
		if(Validator.isNotNullOrEmpty(parentIds)){
			return fail(EnumSvrResult.ERROR_DEL_MENU_PARENT);
		}
		menuService.deleteBatchIds(menuIds);
		return success();
    }
	@ApiOperation("初始化资源")
	@GetMapping("initMenu")
	public Result ininMenu(HttpServletRequest request, @ApiIgnore @LoginUser NowUser nowUser,
			@ApiIgnore @RequestHeader String token) {
		Map<String,Map<String, String>> allMaps = AnnoManageUtil.getRequestMappingMethod("com.bms.admin");
		for (Map.Entry<String,Map<String, String>> entry : allMaps.entrySet()) {
			Menu menu = makeMenu("",entry.getKey(), nowUser.getUsername(),0L);
			menuService.insert(menu);
			Map<String, String> ziMens = entry.getValue();
			for(Map.Entry<String, String> entry2 : ziMens.entrySet()){
				Menu menu2 = makeMenu(entry2.getKey(),entry2.getValue(), nowUser.getUsername(),menu.getId());
				menuService.insert(menu2);
			}
		}
		return error();
	}
	
	private Menu makeMenu(String perms,String title,String username,Long parentId){
		Menu menu = new Menu();
		menu.setPerms(perms);
		menu.setTitle(title);
		menu.setSorts(100);
		menu.setParentId(parentId);
		menu.setCreateTime(new Date());
		menu.setCreateUser(username);
		menu.setUpdateTime(new Date());
		return menu;
	}

}
